using PKGames.Audio;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace PKGames
{
	public class TapAction : MonoBehaviour
	{
		[SerializeField]
		private Button _uiButton;

		[SerializeField]
		private RectTransform _parentAnimator;

		private const float AnimationFirstCycleDuration = 0.15f;

		private const float AnimationSecondCycleDuration = 0.2f;

		private const float AnimationThirdCycleDuration = 0.1f;

		private const float StartingScale = 1f;

		private const float AnimationFirstCycleScale = 0.9f;

		private const float AnimationSecondCycleScale = 1.1f;

		private const float AnimationThirdCycleScale = 1f;

		private bool _clicked;

		private GraphicRaycaster UiRaycaster
		{
			get;
			set;
		}

		public virtual void Start()
		{
			_uiButton.onClick.AddListener(OnClick);
		}

		public void AddTapActionToButton(UnityAction action)
		{
			_uiButton.onClick.AddListener(action);
		}

		private void OnClick()
		{
			if (!_clicked)
			{
				_clicked = true;
				SetAnimationStartingState();
				StartCoroutine(RunAnimation());
			}
		}

		private void SetAnimationStartingState()
		{
			_parentAnimator.localScale = new Vector3(1f, 1f, 1f);
		}

		private IEnumerator RunAnimation()
		{
			TurnOffRaycastTargets();
			MonoSingleton<AudioManager>.Instance.Play("confirm");
			yield return ScaleParentAnimator(0.15f, 1f, 0.9f);
			yield return ScaleParentAnimator(0.2f, 0.9f, 1.1f);
			yield return ScaleParentAnimator(0.1f, 1.1f, 1f);
			yield return null;
			yield return ExecuteAfterButtonAnimation();
			TurnOnRaycastTargets();
			yield return null;
			_clicked = false;
		}

		private IEnumerator ScaleParentAnimator(float animationDuration, float startScale, float targetScale)
		{
			float animationTime2 = 0f;
			AnimationCurve animCurve = AnimationCurve.EaseInOut(0f, startScale, animationDuration, targetScale);
			while (animationTime2 <= animationDuration)
			{
				float scaleValue = animCurve.Evaluate(animationTime2);
				_parentAnimator.localScale = new Vector3(scaleValue, scaleValue, scaleValue);
				animationTime2 += Time.deltaTime;
				animationTime2 = Mathf.Clamp01(animationTime2);
				yield return null;
			}
		}

		protected virtual IEnumerator ExecuteAfterButtonAnimation()
		{
			yield return null;
		}

		private void TurnOffRaycastTargets()
		{
			if (UiRaycaster != null)
			{
				UiRaycaster.enabled = false;
			}
		}

		private void TurnOnRaycastTargets()
		{
			if (UiRaycaster != null)
			{
				UiRaycaster.enabled = true;
			}
		}
	}
}
